package com.chijun.mform.create.control;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.chijun.mform.R;
import com.chijun.mform.create.dialog.ISelectOptionReFormField;
import com.chijun.mform.create.dialog.OptionReFieldDialog;
import com.chijun.mform.create.field.IFieldOptionListener;
import com.chijun.mform.create.mode.FormConfig;
import com.chijun.mform.create.mode.FormField;
import com.chijun.mform.create.mode.FormFieldOption;
import com.example.ccj.u.StringUtils;
import com.example.ccj.u.ToastUtils;
import com.example.ccj.u.server.MyObserver;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 添加选项的Adapter
 * 2024年4月24日21:08:57
 */
public class FieldAddOptionAdapter extends RecyclerView.Adapter<FieldAddOptionAdapter.ViewHolder>{
    List<FormFieldOption> optionList;
    FormConfig formConfig;

    /**
     * @param fieldId 字段id
     * @param formConfig 表单配置
     */
    public FieldAddOptionAdapter(long fieldId, FormConfig formConfig){
        optionList = formConfig.getFormFieldOptionMap().get(fieldId);
        this.formConfig = formConfig;
    }

    @NonNull
    @Override
    public FieldAddOptionAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new FieldAddOptionAdapter.ViewHolder(LayoutInflater.from(parent.getContext()).
                inflate(R.layout.adapter_field_add_option, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull FieldAddOptionAdapter.ViewHolder holder, int position) {
        FormFieldOption s = optionList.get(position);
        holder.id.setText(String.valueOf(position + 1));
        holder.optionText.setText(s.content);
        holder.mIvDelete.setOnClickListener(getDeleteClickListener(position));
        //设置选项关联的字段名称显示
        getFieldNameString(holder.re,s);
        //关联字段点击回调
        holder.mIvRe.setOnClickListener(v -> {

                List<FormField> canReField = new ArrayList<>();
                for (FormField formField : formConfig.getFormFieldList()) {
                    if (formField.getId() != s.fieldId) {
                        canReField.add(formField);
                    }
                }

                if (canReField.isEmpty()) {
                    ToastUtils.showShort("该表单无可关联的字段，需要存在多条字段");
                    return;
                }

                if (!formConfig.getFieldOptionReMap().containsKey(s.id)) {
                    formConfig.getFieldOptionReMap().put(s.id,new ArrayList<>());
                }

                List<FormField> formFields = formConfig.getFieldOptionReMap().get(s.id);

                OptionReFieldDialog optionReFieldDialog = new OptionReFieldDialog(v.getContext(),s, canReField, formFields, new ISelectOptionReFormField() {
                    @Override
                    public void add(FormField formField) {
                        s.isRe = true;
                        getFieldNameString(holder.re,s);
                    }

                    @Override
                    public void remove(FormField formField) {
                        getFieldNameString(holder.re,s);
                    }
                });
                optionReFieldDialog.show();

        });
    }

    private void getFieldNameString(TextView re,FormFieldOption formFieldOption){
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                List<FormField> optionReField = formConfig.getFieldOptionReMap().get(formFieldOption.id);
                if (optionReField != null &&  !optionReField.isEmpty()) {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (FormField formField : optionReField) {
                        stringBuilder.append(formField.getName()).append(",");
                    }
                    e.onNext(stringBuilder.toString());
                }
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new MyObserver<String>() {
                    @Override
                    public void onNext(String s) {
                        if (StringUtils.isEmpty(s)) {
                            re.setVisibility(View.GONE);
                            formFieldOption.isRe = false;
                        } else {
                            re.setVisibility(View.VISIBLE);
                            re.setText(s);
                        }
                    }
                });
    }

    private View.OnClickListener getDeleteClickListener(int position){
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                notifyRemove(position);
            }
        };
    }

    @Override
    public int getItemCount() {
        return optionList == null ? 0 : optionList.size();
    }

    public static class ViewHolder extends  RecyclerView.ViewHolder{
        ImageView mIvDelete;
        ImageView mIvRe;
        EditText optionText;
        TextView id,re;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            mIvDelete = itemView.findViewById(R.id.adapter_field_add_option_delete);
            optionText = itemView.findViewById(R.id.adapter_field_add_option_text);
            id = itemView.findViewById(R.id.adapter_field_add_option_id);
            mIvRe = itemView.findViewById(R.id.adapter_field_add_option_re);
            re = itemView.findViewById(R.id.adapter_field_add_option_re_f);

        }
    }

    private void notifyRemove(int position){
        FormFieldOption remove = optionList.remove(position);
        notifyItemRemoved(position);
        //重新加载从删除位置往下的所有item，如果删除的是中间，自删除的位置到最后开始是做重新添加操作
        //避免下表越界等错误
        notifyItemRangeRemoved(position,getItemCount());
        //选项删除后删除关联的字段
        formConfig.getFieldOptionReMap().remove(remove.id);
    }

}
